package com.example.seabedmusic.views;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.seabedmusic.R;
import com.example.seabedmusic.adapter.SongAdapter;
import com.example.seabedmusic.contract.MusicContract;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.presenter.MusicPresenter;

import java.util.ArrayList;
import java.util.List;

public class MusicFragment extends Fragment implements MusicContract.IMusicView {

    private MusicContract.IMusicPresenter mPresenter;

    /* --------------- 三个列表 --------------- */
    private List<Song> songList      = new ArrayList<>();
    private List<Song> recentList    = new ArrayList<>();
    private List<Song> searchList    = new ArrayList<>();

    /* --------------- 适配器 --------------- */
    private SongAdapter songAdapter, recentAdapter, searchAdapter;

    /* --------------- 控件 --------------- */
    private RecyclerView songRv, recentRv, searchResultRv;
    private ImageView coverIv;          // 白框封面
    private EditText searchEt;
    private View functionButtons;       // 功能按钮区域
    private LinearLayout rootLayout;    // 根布局

    private boolean isInSearchMode = false;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_music, container, false);
        rootLayout = (LinearLayout) root;

        /* 1. 搜索栏 */
        searchEt = root.findViewById(R.id.search_bar);
        searchEt.setOnEditorActionListener((v, actionId, event) -> {
            String keyword = v.getText().toString().trim();
            if (!keyword.isEmpty()) {
                enterSearchMode();
                coverIv.setVisibility(View.GONE);
                mPresenter.search(keyword);
            }
            return true;
        });

        // 添加搜索框文本变化监听
        searchEt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!isInSearchMode) {
                    enterSearchMode();
                }
                return false;
            }
        });

        /* 2. 四个功能按钮 */
        root.findViewById(R.id.btn_daily).setOnClickListener(v -> {
            exitSearchMode();
            coverIv.setVisibility(View.GONE);
            searchResultRv.setVisibility(View.GONE);
            songRv.setVisibility(View.VISIBLE);
            mPresenter.getDaily();
            navigateToDailyRecommend();
        });
        root.findViewById(R.id.btn_fav).setOnClickListener(v -> {
            exitSearchMode();
            coverIv.setVisibility(View.GONE);
            searchResultRv.setVisibility(View.GONE);
            songRv.setVisibility(View.VISIBLE);
            mPresenter.getFav();
        });
        root.findViewById(R.id.btn_hot).setOnClickListener(v -> {
            // 热歌排行直接跳转，不需要退出搜索模式的处理
            navigateToHotMusic();
        });
        root.findViewById(R.id.btn_random).setOnClickListener(v -> {
            exitSearchMode();
            coverIv.setVisibility(View.GONE);
            searchResultRv.setVisibility(View.GONE);
            songRv.setVisibility(View.VISIBLE);
            // 使用新的随机音乐API
            mPresenter.getRandomMusic();
        });

        /* 3. 封面 & 三个 RecyclerView */
        coverIv        = root.findViewById(R.id.song_cover);
        songRv         = root.findViewById(R.id.song_list);
        recentRv       = root.findViewById(R.id.recent_list);
        searchResultRv = root.findViewById(R.id.search_result_list);
        functionButtons = root.findViewById(R.id.function_buttons);

        songAdapter   = new SongAdapter(songList);
        recentAdapter = new SongAdapter(recentList);
        searchAdapter = new SongAdapter(searchList);

        songRv.setLayoutManager(new LinearLayoutManager(getContext()));
        recentRv.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.HORIZONTAL, false));
        searchResultRv.setLayoutManager(new LinearLayoutManager(getContext()));

        songRv.setAdapter(songAdapter);
        recentRv.setAdapter(recentAdapter);
        searchResultRv.setAdapter(searchAdapter);

        coverIv.setVisibility(View.GONE);
        searchResultRv.setVisibility(View.GONE);

        /* 4. presenter */
        mPresenter = new MusicPresenter(this, getContext());
        mPresenter.getDaily();
        mPresenter.getRecent();

        return root;
    }

    /**
     * 进入搜索模式
     */
    private void enterSearchMode() {
        isInSearchMode = true;
        searchResultRv.setVisibility(View.VISIBLE);
        songRv.setVisibility(View.GONE);
        functionButtons.setVisibility(View.GONE);
        coverIv.setVisibility(View.GONE);

        // 隐藏软键盘
        hideKeyboard();
    }

    private void navigateToDailyRecommend() {
        try {
            Intent intent = new Intent(getActivity(), DailyRecommendActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            showToast("每日推荐功能正在开发中");
            e.printStackTrace();
        }
    }

    /**
     * 退出搜索模式
     */
    private void exitSearchMode() {
        isInSearchMode = false;
        searchResultRv.setVisibility(View.GONE);
        songRv.setVisibility(View.VISIBLE);
        functionButtons.setVisibility(View.VISIBLE);
        searchEt.setText("");

        // 清除焦点
        searchEt.clearFocus();

        // 隐藏软键盘
        hideKeyboard();

        // 清空搜索结果
        searchList.clear();
        searchAdapter.notifyDataSetChanged();
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && searchEt != null) {
            imm.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
        }
    }

    private void navigateToHotMusic() {
        try {
            Intent intent = new Intent(getActivity(), HotMusicActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            // 如果HotMusicActivity不存在，显示提示
            showToast("热歌排行功能正在开发中");
            e.printStackTrace();
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 设置根布局的点击监听器来退出搜索
        rootLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInSearchMode) {
                    exitSearchMode();
                }
            }
        });

        // 阻止点击事件传递到子视图，但排除功能按钮
        setupClickInterception();
    }

    /**
     * 设置点击事件拦截，防止子视图处理点击事件
     */
    private void setupClickInterception() {
        // 为所有子视图设置点击监听器，阻止事件传递
        setClickInterceptor(rootLayout);
    }

    private void setClickInterceptor(View view) {
        if (view instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) view;
            for (int i = 0; i < group.getChildCount(); i++) {
                View child = group.getChildAt(i);

                // 跳过功能按钮，让它们正常处理点击
                if (child.getId() == R.id.btn_daily ||
                        child.getId() == R.id.btn_fav ||
                        child.getId() == R.id.btn_hot ||
                        child.getId() == R.id.btn_random) {
                    continue;
                }

                setClickInterceptor(child);
            }
        } else if (view != searchEt) { // 跳过搜索框
            // 为叶子视图设置点击监听器
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 阻止事件传递，让根布局的点击监听器处理
                }
            });
        }
    }

    /* =============== 下面都是接口回调 =============== */

    @Override
    public void showSongs(List<Song> songs) {
        // 根据当前模式决定更新哪个列表
        if (isInSearchMode) {
            // 搜索模式：更新搜索结果列表
            searchList.clear();
            searchList.addAll(songs);
            searchAdapter.notifyDataSetChanged();

            // 搜索模式下显示封面
            if (!songs.isEmpty()) {
                Song firstSong = songs.get(0);
                if (firstSong.getCover() != null && !firstSong.getCover().isEmpty()) {
                    Glide.with(this)
                            .load(firstSong.getCover())
                            .placeholder(R.drawable.ic_music_note)
                            .error(R.drawable.ic_music_note)
                            .into(coverIv);
                    coverIv.setVisibility(View.VISIBLE);
                    android.util.Log.d("MusicFragment", "显示封面: " + firstSong.getCover());
                } else {
                    coverIv.setVisibility(View.GONE);
                    android.util.Log.d("MusicFragment", "无封面图片");
                }
            } else {
                coverIv.setVisibility(View.GONE);
            }
        } else {
            // 正常模式：更新主歌曲列表（每日推荐、我的收藏、随机音乐）
            songList.clear();
            songList.addAll(songs);
            songAdapter.notifyDataSetChanged();

            // 正常模式下隐藏封面，只显示列表
            coverIv.setVisibility(View.GONE);
        }

        // 显示提示信息
        if (!songs.isEmpty() && isInSearchMode) {
            Song firstSong = songs.get(0);
            if (firstSong.getArtist() != null) {
                showToast("找到歌曲: " + firstSong.getTitle() + " - " + firstSong.getArtist());
            }
        }
    }
    @Override
    public void showRecent(List<Song> songs) {
        recentList.clear();
        recentList.addAll(songs);
        recentAdapter.notifyDataSetChanged();

        // 更新最近播放区域的显示状态
        if (recentRv != null) {
            if (songs.isEmpty()) {
                recentRv.setVisibility(View.GONE);
            } else {
                recentRv.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {
        // 可以在这里显示加载进度条
    }

    @Override
    public void hideLoading() {
        // 可以在这里隐藏加载进度条
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 清理资源
        if (mPresenter != null) {
            // 如果Presenter有需要释放的资源，可以在这里调用
        }
    }
}